﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Tulde.MP3tunes.Animation
{
    public abstract class AnimationBase
    {
        public event EventHandler AnimationCompleted;

        protected virtual void OnAnimationCompleted(EventArgs e)
        {
            if (AnimationCompleted != null)
                AnimationCompleted(this, e);
        }

        protected virtual string ResourceKey
        {
            get
            {
                return GetType().FullName;
            }
        }

        protected abstract Storyboard CreateStoryboard();
        protected abstract void ApplyValues(Storyboard storyboard, TimeSpan? duration);

        public virtual void Apply<T>(FrameworkElement element, T args) where T : AnimationArguments
        {
            if (element == null)
                throw new ArgumentNullException("element");

            Storyboard storyboard = null;

            if (element.Resources.Contains(ResourceKey))
            {
                storyboard = element.Resources[ResourceKey] as Storyboard;
                storyboard.Pause();
            }
            else
            {
                storyboard = CreateStoryboard();
                element.Resources.Add(ResourceKey, storyboard);

                foreach (var timeline in storyboard.Children)
                {
                    Storyboard.SetTarget(timeline, element);
                }
            }

            ApplyValues(storyboard, args.Duration);

            if (args.Callback != null)
                storyboard.Completed += (e, a) =>
                {
                    args.Callback(e, a);
                };
            else
            {
                storyboard.Completed += OnStoryboardCompleted;
            }
            storyboard.Begin();
        }

        protected virtual void OnStoryboardCompleted(object sender, EventArgs e)
        {
            OnAnimationCompleted(EventArgs.Empty);
        }


    }
}
